//
//  PywVerifySMSCodeView.m
//  PywSdk
//
//  Created by Jade on 16/8/30.
//  Copyright © 2016年 zero. All rights reserved.
//

#import "PywVerifySMSCodeView.h"
#import "PywMasonry.h"
#import "UILabel+Pyw.h"
#import "PywTextFieldView.h"
#import "UIButton+Pyw.h"
#import "PywCommonManager.h"
#import "PywGetSmsCodeApi.h"
#import "PywMBProgressHUD+Pyw.h"
#import "PywResourceUtils.h"
#import "PywCheckSmsCodeApi.h"
#import "PywCheckSmsCodeAndBindApi.h"
#import "MutableDictionary.h"
#import "PywBuriedManager.h"

@interface PywVerifySMSCodeView()<PywTextFieldViewDelegate>
@property (nonatomic, strong) UILabel               *propmtLabel;       // 提示信息
@property (nonatomic, strong) PywTextFieldView      *validCodeView;     // 验证码输入框
@property (nonatomic, strong) UIButton              *nextBtn;           // 下一步按钮

@property (nonatomic, copy) NSString                *phoneNum;       // 手机号码
@property (nonatomic, copy) NSString                *smsType;           // 获取验证码场景类型

@property (nonatomic, strong) PywGetSmsCodeApi      *getSmsCodeApi;     // 获取验证码请求
@property (nonatomic, strong) PywCheckSmsCodeApi    *checkSmsCodeApi;   // 校验验证码请求
@property (nonatomic, strong) PywCheckSmsCodeAndBindApi *checkSmsCodeAndBindApi;//验证验证码并绑定

@property (nonatomic,copy) NSString *status;
@end

@implementation PywVerifySMSCodeView

- (instancetype)initWithStatus:(NSString *)status
                      phoneNum:(NSString *)phoneNum
                         smsType:(NSString *)smsType
{
    self = [super init];
    if (self) {
        self.phoneNum = phoneNum;
        self.smsType = smsType;
        self.status = status;
        [self setUp];
    }
    return self;
}

#pragma mark - setUp
- (void)setUp
{
    [self addSubview:self.propmtLabel];
    [self addSubview:self.validCodeView];
    [self addSubview:self.nextBtn];
    
    [self addConstraints];
}

- (void)addConstraints
{
    WEAK_SELF;
    [self.propmtLabel mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.equalTo(weakSelf.mas_top).offset(80);
        make.width.equalTo(weakSelf.mas_width).multipliedBy(0.85);
    }];
    
    [self.validCodeView mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.equalTo(weakSelf.propmtLabel.mas_bottom).offset(20);
        make.width.equalTo(weakSelf.propmtLabel.mas_width);
        make.height.equalTo(@40);
    }];
    
    [self.nextBtn mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.equalTo(weakSelf.validCodeView.mas_bottom).offset(40);
        make.width.height.equalTo(weakSelf.validCodeView);
    }];
}

#pragma mark - getter

- (PywGetSmsCodeApi *)getSmsCodeApi
{
    if (!_getSmsCodeApi) {
        _getSmsCodeApi = [PywGetSmsCodeApi manager];
    }
    return _getSmsCodeApi;
}

- (PywCheckSmsCodeApi *)checkSmsCodeApi
{
    if (!_checkSmsCodeApi) {
        _checkSmsCodeApi = [PywCheckSmsCodeApi manager];
    }
    return _checkSmsCodeApi;
}

- (PywCheckSmsCodeAndBindApi *)checkSmsCodeAndBindApi
{
    if (!_checkSmsCodeAndBindApi) {
        _checkSmsCodeAndBindApi = [PywCheckSmsCodeAndBindApi manager];
    }
    return _checkSmsCodeAndBindApi;
}

- (UILabel *)propmtLabel
{
    if (!_propmtLabel) {
        _propmtLabel = [UILabel labelWithText:nil
                                textAlignment:NSTextAlignmentLeft
                                     fontSize:12
                                    textColor:[UIColor blackColor]];
        
        NSString *phone = self.phoneNum;
        NSString *propmtStr = [NSString stringWithFormat:@"已向%@发送验证码",phone];
        NSMutableAttributedString *propmtMessage = [[NSMutableAttributedString alloc] initWithString:propmtStr];
        [propmtMessage addAttribute:NSForegroundColorAttributeName value:RGB(252, 177, 14, 1) range:NSMakeRange(2, phone.length)];
        _propmtLabel.attributedText = propmtMessage;
    }
    return _propmtLabel;
}
- (PywTextFieldView *)validCodeView
{
    if (!_validCodeView) {
        _validCodeView = [PywTextFieldView validCodeTextFieldWithLeftImg:nil
                                                         TextPlaceholder:@"请输入验证码"
                                                                Delegate:self
                                                             ButtonTitle:@"获取验证码"];
        [[PywCommonManager manager] startTimeWithButton:_validCodeView.operationBtn];
        [_validCodeView setAccessibilityId:@"binphone_code"];
    }
    return _validCodeView;
}
- (UIButton *)nextBtn
{
    if (!_nextBtn) {
        _nextBtn = [UIButton buttonWithBackgroundColor:RGB(252, 177, 14, 1)
                                          cornerRadius:20
                                            titleColor:[UIColor whiteColor]
                                    titleLabelFontSize:18
                                                 title:@"下一步"];
        
        [_nextBtn addTarget:self action:@selector(verifySmsCode) forControlEvents:UIControlEventTouchUpInside];
        [_nextBtn setAccessibilityIdentifier:@"binphone_next"];
    }
    return _nextBtn;
}

/**
 *  获取短信验证码  传入参数
 *
 *  @return <#return value description#>
 */
- (MutableDictionary *)requestGetValidCodeParams
{
    NSString *phoneNum = [self.phoneNum stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *smsType = [self.smsType stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    MutableDictionary *param = [[MutableDictionary alloc] init];
    [param setObject:phoneNum forKey:@"phone"];
    [param setObject:smsType forKey:@"smstype"];
    return param;
}

/**
 *  校验短信验证码  传入参数
 *
 *  @return <#return value description#>
 */
- (MutableDictionary *)requestCheckValidCodeParams{
    NSString *smsCode = [self.validCodeView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *phoneNumber = [self.phoneNum stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *smsType = [self.smsType stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    MutableDictionary *param = [[MutableDictionary alloc] init];
    [param setObject:phoneNumber forKey:@"phone"];
    [param setObject:smsCode forKey:@"smscode"];
    [param setObject:smsType forKey:@"smstype"];
    return param;
}

#pragma mark - Actoins
/**
 *  验证验证码
 */
- (void)verifySmsCode
{
    [self endEditing:YES];
    // 判断是否已填写验证码
    if (self.validCodeView.text.length <= 0) {
        
        [PywMBProgressHUD showError:@"请填写验证码" toView:self];
    } else {
        if ([self.status integerValue] == 1) {
            [self requestCheckSmsCodeBindPassport];
        }else {
            [self requestcheckSmsCode];
        }
    }
}
#pragma mark - Request
/**
 *  验证验证码
 */
- (void)requestcheckSmsCode
{
    WEAK_SELF;
    [[PywBuriedManager manager] saveUserActionDataWithPageSn:@"5" actionSn:@"11" typeSn:@"3"];
    [self.checkSmsCodeApi requestCheckSmsCodeWithParams:[self requestCheckValidCodeParams] success:^(NSString *status, id anyObjct) {
        if (weakSelf.verifyCodeComplete) {
            weakSelf.verifyCodeComplete(weakSelf.status,weakSelf.phoneNum);
        }
        
    } fail:^(NSError *error) {
        self.validCodeView.text = @"";
    }];
}

/**
 *  验证验证码并绑定通行证
 */
- (void)requestCheckSmsCodeBindPassport
{
    NSString *passport = self.phoneNum;
    NSString *smsCode = [self.validCodeView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *smsType = self.smsType;
    
    MutableDictionary *dictionary = [[MutableDictionary alloc] init];
    [dictionary setObject:passport forKey:@"passport"];
    [dictionary setObject:smsCode forKey:@"smsCode"];
    [dictionary setObject:smsType forKey:@"smsType"];
    WEAK_SELF;
    [self.checkSmsCodeAndBindApi requestCheckSmsCodeAndBindWithParams:dictionary success:^(NSString *status, id anyObjct) {
        if ([status integerValue] == CheckSmsTypeBindSuccess) {
            if (weakSelf.verifyCodeComplete) {
                weakSelf.verifyCodeComplete(weakSelf.status,weakSelf.phoneNum);
            }
        }
    } fail:^(NSError *error) {
    }];
}

#pragma mark - PywTextFieldViewDelegate
- (void)textFieldView:(PywTextFieldView *)textField buttonEvent:(UIButton *)btn
{
    WEAK_SELF;
    [[PywBuriedManager manager] saveUserActionDataWithPageSn:@"5" actionSn:@"12" typeSn:@"3"];
    [self.getSmsCodeApi requestGetSmsCodeWithParams:[self requestGetValidCodeParams] success:^(NSString *status, id anyObjct) {
        
        [[PywCommonManager manager] startTimeWithButton:weakSelf.validCodeView.operationBtn];
    } fail:^(NSError *error) {
        
    }];
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.validCodeView becomeFirstResponder];
}


@end
